package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.DON_VI_TCD;
import model.DON_VI_TCM;
import net.sf.json.JSONObject;


@WebServlet("/DON_VI_TCServlet")
public class DON_VI_TCServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DON_VI_TCD dao;
       
    /**
     * @function constructor DON_VI_TCServlet
     * @throws Exception 
     * @see HttpServlet#HttpServlet()
     */
    public DON_VI_TCServlet() throws Exception {
        super();
        this.dao = new DON_VI_TCD();
    }
    
    /**
	 * Destruction of the servlet.
	 */
	public void destroy() {
		super.destroy();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
		
		String flag = request.getParameter("flag");
		
		try {
			if (flag == null || "".equals(flag.trim())) {
				showDVTC(request, response);
			}else if ("add".equals(flag.trim())) {
				String ma = request.getParameter("ma_don_vi");
				String ten = request.getParameter("ten");
				String cap = request.getParameter("cap");
				String id_don_vi_tc_cha = request.getParameter("id_don_vi_tc_cha");
				String id_loai_don_vi_tc = request.getParameter("id_loai_don_vi_tc");
				
				addDVTC(ma,ten,Integer.parseInt(cap), Integer.parseInt(id_don_vi_tc_cha), Integer.parseInt(id_loai_don_vi_tc),request,response);
			}else if ("edit".equals(flag.trim())) {
				String id = request.getParameter("id_don_vi_tc");
				String ma = request.getParameter("ma_don_vi");
				String ten = request.getParameter("ten");
				String cap = request.getParameter("cap");
				String id_don_vi_tc_cha = request.getParameter("id_don_vi_tc_cha");
				String id_loai_don_vi_tc = request.getParameter("id_loai_don_vi_tc");
				editDVTC(Integer.parseInt(id), ma,ten,Integer.parseInt(cap), Integer.parseInt(id_don_vi_tc_cha), Integer.parseInt(id_loai_don_vi_tc), request, response);
			}else if ("remove".equals(flag.trim())) {
				String[] id = request.getParameter("id").split(",");
				for(int i = 0; i < id.length; i++){
					deleteDVTC(Integer.parseInt(id[i]), request, response);
				}				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @function show DON_VI_TC
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void showDVTC(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String pageCount = request.getParameter("page");
		String rowsCount = request.getParameter("rows");
		String search=request.getParameter("searchTen")==null?"":request.getParameter("searchTen");
		
		int page = (pageCount == null || "".equals(pageCount)) ? 1 : Integer.valueOf(pageCount);
		int rows = (rowsCount == null || "".equals(rowsCount)) ? 10 : Integer.valueOf(rowsCount);
		
		int offSet = (page - 1) * rows;
		int allCount = dao.searchDVTC(search).size();
		
		returnMap.put("total", allCount);
		returnMap.put("rows", dao.getAlls(search, offSet, rows));
		
		String returnString = JSONObject.fromObject(returnMap).toString();
		PrintWriter out = response.getWriter();
		out.println(returnString);
		out.flush();
		out.close();
	}
	
	/**
	 * @function add DON_VI_TC
	 * @param ma
	 * @param ten
	 * @param cap
	 * @param id_don_vi_tc_cha
	 * @param id_loai_don_vi_tc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void addDVTC(String ma, String ten, int cap,  int id_don_vi_tc_cha, int id_loai_don_vi_tc, HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		DON_VI_TCM dvtc = new DON_VI_TCM();
		dvtc.setMa_don_vi(ma);
		dvtc.setTen(ten);
		dvtc.setCap(cap);
		dvtc.setId_don_vi_tc_cha(id_don_vi_tc_cha);
		dvtc.setId_loai_don_vi_tc(id_loai_don_vi_tc);
		if(dao.Insert(dvtc)==true){
			map.put("success", "true");
			map.put("msg", "Thêm thành công");
		} else {
			map.put("success", "false");
			map.put("msg", "Lỗi thêm dữ liệu");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
	
	/**
	 * @function add DON_VI_TC
	 * @param id
	 * @param ma
	 * @param ten
	 * @param cap
	 * @param id_don_vi_tc_cha
	 * @param id_loai_don_vi_tc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void editDVTC(int id_don_vi_tc, String ma, String ten, int cap, int id_don_vi_tc_cha, int id_loai_don_vi_tc, HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		DON_VI_TCM dvtc = new DON_VI_TCM();
		dvtc.setId_don_vi_tc(id_don_vi_tc);
		dvtc.setMa_don_vi(ma);
		dvtc.setTen(ten);
		dvtc.setCap(cap);
		dvtc.setId_don_vi_tc_cha(id_don_vi_tc_cha);
		dvtc.setId_loai_don_vi_tc(id_loai_don_vi_tc);
		if(dao.Update(dvtc)==true){
			map.put("success", "true");
			map.put("msg", "Sửa thành công");
		} else {
			map.put("success", "false");
			map.put("msg", "Lỗi sửa dữ liệu");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
	
	/**
	 * @function delete DON_VI_TC
	 * @param id_don_vi_tc
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	private void deleteDVTC(int id_don_vi_tc, HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if(dao.Delete(id_don_vi_tc)==true){
			map.put("success", "true");
			map.put("msg", "Xóa thành công");
		} else {
			map.put("success", "false");
			map.put("msg", "Lỗi xóa dữ liệu");
		}
		String returnFlag = JSONObject.fromObject(map).toString();
		PrintWriter out = response.getWriter();
		out.println(returnFlag);
		out.flush();
		out.close();
	}
}